package com.mbigger.netty.ch2.handler;

import java.nio.charset.Charset;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FirstServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 收数据
        ByteBuf byteBuf = (ByteBuf) msg;

        log.info("服务端读到数据: {}", byteBuf.toString(Charset.forName("utf-8")));
        // 回复数据到客户端
        ByteBuf out = getByteBuf(ctx);
        log.info("服务端写出数据: {}", out.toString(Charset.forName("utf-8")));
        ctx.channel().writeAndFlush(out);
        // ctx.channel().writeAndFlush(123);
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
        byte[] bytes = "bug第一行".getBytes(Charset.forName("utf-8"));

        ByteBuf buffer = ctx.alloc().buffer();

        buffer.writeBytes(bytes);

        return buffer;
    }
}
